<template>
	<div class="sys-user-container">
		<el-row :gutter="8" style="width: 100%;height: 100%;">
			<el-col :xs="24" style="display:flex;flex-direction:column;">
                <el-card class="contract_tip_bar">
                    <el-row> 
                        <el-col :span="1">
                            <el-icon :size="20" color="#d87e29">
                                <Warning />
                            </el-icon>
                        </el-col>
                        <el-col :span="22">
                            提醒:有 <span class="tipNum">3</span>
                            名员工合同即将到期或已到期，请尽快处理! 
                            <span class="settingnotice">设置提醒</span>
                        </el-col>
                        <el-col :span="1" class="mgright">
                            <el-icon :size="20" color="#d87e29">
                                <Close />
                            </el-icon>
                        </el-col>
                    </el-row>
                </el-card>
				<el-card shadow="hover" class="tabSearch_Bar" :body-style="{ paddingBottom: '0' }">
					<TableSearch :search="tb.tableData.search" @search="onSearch" />
				</el-card>
				<el-card class="full-table" shadow="hover" style="margin-top: 8px">
					<Table ref="tableRef" v-bind="tb.tableData" :getData="getData" :exportChangeData="exportChangeData" @sortHeader="onSortHeader" @selectionChange="tableSelection">
						<template #command>
							<el-button type="primary" icon="ele-RefreshRight" @click="openAddUser" v-auth="'sysUser:add'"> 更新当前合同 </el-button>
                            <el-dropdown size="small" split-button class="spaceDropDown">
								新增历史合同
								<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item icon="ele-SemiSelect">单个新增</el-dropdown-item>
									<el-dropdown-item icon="ele-Flag">批量新增</el-dropdown-item> 
								</el-dropdown-menu>
								</template>
							</el-dropdown>
							<el-button icon="ele-Download" v-auth="'sysUser:add'"> 导出 </el-button>
							<el-button icon="ele-Stamp" v-auth="'sysUser:add'"> 合同审批 </el-button>
						</template>
						<template #sex="scope">
							<el-tag type="success" v-if="scope.row.sex === 1"> 男 </el-tag>
							<el-tag type="danger" v-else> 女 </el-tag>
						</template>
						<template #orgName="scope">
							{{scope.row.sysOrg.name}}
						</template> 
						<template #joinDate="scope">
							{{ formatDate(new Date(scope.row.joinDate), 'YYYY-mm-dd') }}
						</template>
						<template #age="scope">
							{{ frmatYear(new Date(scope.row.birthday)) }}
						</template>
						<template #status="scope">
							<el-tag type="success" v-if="scope.row.status === 1"> 在职 </el-tag>
							<el-tag type="danger" v-else> 离职 </el-tag>
						</template>
						<template #action="scope">
							<el-dropdown>
								<el-button icon="ele-MoreFilled" size="small" text type="primary" style="padding-left: 12px" />
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item icon="ele-EditPen" @click="delUser(scope.row)" divided> 编辑 </el-dropdown-item>
										<el-dropdown-item icon="ele-Unlock" @click="delUser(scope.row)" divided> 续签合同 </el-dropdown-item>
										<el-dropdown-item icon="ele-Position" @click="delUser(scope.row)" divided> 发起续签审批 </el-dropdown-item>
										<el-dropdown-item icon="ele-Switch" @click="delUser(scope.row)" divided> 变更合同 </el-dropdown-item>
										<el-dropdown-item icon="ele-SwitchButton" @click="delUser(scope.row)" divided> 终止合同 </el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</template>
					</Table>
				</el-card>
			</el-col>
		</el-row>

		<EditEmployee ref="editUserRef" :title="state.editUserTitle" :orgData="state.orgTreeData" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="sysUser">
import {SemiSelect,Flag} from '@element-plus/icons-vue'
import { onMounted, reactive, ref,defineAsyncComponent, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { formatDate,frmatYear } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import OrgTree from '/@/views/org/manager/component/orgTree.vue';
import EditEmployee from '/@/views/employee/manage/component/editEmployee.vue';

import { getAPI } from '/@/utils/axios-utils';
import { EmployeeApi, SysOrgApi } from '/@/api-services/api';
import { SysUser, SysOrg } from '/@/api-services/models'; 
import { fa } from 'element-plus/es/locale';

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const tableRef = ref<RefType>();
const orgTreeRef = ref<InstanceType<typeof OrgTree>>();
const editUserRef = ref<InstanceType<typeof EditEmployee>>();

const state = reactive({
	loading: false,
	selectlist: [] as EmptyObjectType[],
	userData: [] as Array<SysUser>,
	orgTreeData: [] as Array<SysOrg>,
	editUserTitle: '',
});


const tb = reactive<TableDemoState>({
	tableData: {
		// 表头内容（必传，注意格式）
		columns: [
			{ type: 'index', width:50, label: '序号',fixed:'left',align: 'left', isCheck: true },
			{ prop: 'jobNum', width:90, label: '工号',fixed:'left',align: 'left', sortable: 'custom', isCheck: true },
			{ prop: 'realName', width: 90, label: '姓名',fixed:'left', align: 'left',  sortable: 'custom', isCheck: true },		
			{ prop: 'orgName', width: 120, label: '部门',fixed:'left', align: 'left', isCheck: true,'show-overflow-tooltip':true, hideCheck: true},		
			{ prop: 'idCardNum', width: 150, label: '证件号', align: 'left', isCheck: true },		
			{ prop: 'contractNo', width: 130, label: '合同编号', align: 'left', isCheck: true,'show-overflow-tooltip':true, },		
			{ prop: 'contractCo', width: 100, label: '合同公司', align: 'left',isCheck: true,'show-overflow-tooltip':true, },		
			{ prop: 'contractType', width: 80, label: '合同类型', align: 'left', isCheck: true },		
			{ prop: 'contractYear', width: 90, label: '合同期限', align: 'left',  isCheck: true },		
            { prop: 'startDate', width: 100, label: '合同开始日期', align: 'left',isCheck: true },		
			{ prop: 'endDate', width: 100, label: '合同结束日期', align: 'left', isCheck: true },		
			{ prop: 'qdDate', width: 100, label: '合同签订日期', align: 'left', isCheck: true },		
			{ prop: 'zzDate', width: 100, label: '合同终止日期', align: 'left', isCheck: true },		
			{ prop: 'qdNum', width: 90, label: '已签订次数', align: 'left', isCheck: true },		
			{ prop: 'xqspState', width: 90, label: '续签审批状态', align: 'left', fixed: 'right', isCheck: true },		
			{ prop: 'htState', width: 90, label: '合同状态', align: 'left', fixed: 'right', isCheck: true },				
			{ prop: 'action', width: 50, label: '操作', type: 'action', align: 'left', isCheck: true, fixed: 'right', hideCheck: true },
		],
		// 配置项（必传）
		config: {
			isStripe: false, // 是否显示表格斑马纹
			isBorder: true, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: true, // 是否勾选表格多选 
			showSelection: auth('sysUser:delete'), //是否显示表格多选
			pageSize: 10, // 每页条数
			hideExport: false, //是否隐藏导出按钮 
			hidePrint:false,//是否隐藏打印按钮
			exportFileName: '员工资料', //导出报表的文件名，不填写取应用名称
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，type有3种类型：input,date,select）
		search: [
			{ label: '职工状态', prop: 'status', placeholder: '职工状态', required: false, type: 'select',with:150,
                options:[{label:'全部',value:''},{label:'在职',value:'1'},{label:'离职',value:'0'}]
            },
			{ label: '工号', prop: 'jobNum', placeholder: '搜索工号', required: false, type: 'input',with:150 },
			{ label: '姓名', prop: 'realName', placeholder: '搜索姓名', required: false, type: 'input',with:150 },
		],
		param: {
			orgId: -1,
			jobNum: undefined,
			realName: undefined,
			phone: undefined,
		},
		defaultSort: {
			prop: 'orderNo',
			order: 'ascending',
		},
		customPrintFun:function(_param:any,_data:any){
			console.log("===================================AAAAA");
		}
	},
});
 
const getData = (param: any) => {
    return new Promise(function(resolve, reject){ 
        setTimeout(function(){
            let tempData={code: 200,extras: null,message: "",type:"success",result:{
                "page": 1,
                "pageSize": 10,
                "total": 3,
                "totalPages": 1,
                "items": [
                        {
                        "realName": "孙彩丽",
                        "nickName": "孙彩丽",
                        "joinDate":"2001-03-22 00:00:00",
                        "nation": "汉族",
                        "phone": "15201171471",
                        "idCardNum": "12345678900123078",
                        "status": 1,
                        "orgId": 1300000000101,
                        "sysOrg": {
                            "pid": 0,
                            "name": "鹰美（荆门）制衣有限公司",
                            "code": "1001",
                            "orgType": "101",
                            "orderNo": 100,
                            "remark": "大名科技",
                        },
                        "jobNum": "600305",
                        "contractNo":"CJM202206040023",
                        "contractCo":"鹰美(荆门)制衣有限公司",
                        "contractType":"劳动合同",
                        "contractYear":"1",
                        "startDate":"2022-06-04",
                        "endDate":"2023-06-04",
                        "qdDate":"2022-06-04",
                        "zzDate":"",//合同终止日期
                        "qdNum":1,//签订次数
                        "xqspState":"未发起",
                        "htState":"已生效",//合同状态
                        "id": 13392500277061
                        },
                        {
                        "realName": "王五",
                        "nickName": "王五",
                        "joinDate":"2001-03-22 00:00:00",
                        "nation": "汉族",
                        "phone": "15201171471",
                        "idCardNum": "12345678900123122",
                        "status": 1,
                        "orgId": 1300000000101,
                        "sysOrg": {
                            "pid": 0,
                            "name": "IE部",
                            "code": "1001",
                            "orgType": "101",
                            "orderNo": 100,
                            "remark": "大名科技",
                        },
                        "jobNum": "600305",
                        "contractNo":"CJM202206040023",
                        "contractCo":"鹰美(荆门)制衣有限公司",
                        "contractType":"劳动合同",
                        "contractYear":"1",
                        "startDate":"2022-06-04",
                        "endDate":"2023-06-04",
                        "qdDate":"2022-06-04",
                        "zzDate":"",//合同终止日期
                        "qdNum":1,//签订次数
                        "xqspState":"未发起",
                        "htState":"已生效",//合同状态
                        "id": 13392500277062
                        },
                        {
                        "realName": "张三",
                        "nickName": "张三",
                        "joinDate":"2001-03-22 00:00:00",
                        "nation": "汉族",
                        "phone": "15201171471",
                        "idCardNum": "42345678900121465",
                        "status": 1,
                        "orgId": 1300000000101,
                        "sysOrg": {
                            "pid": 0,
                            "name": "企划部",
                            "code": "1001",
                            "orgType": "101",
                            "orderNo": 100,
                            "remark": "大名科技",
                        },
                        "jobNum": "600305",
                        "contractNo":"CJM202206040023",
                        "contractCo":"鹰美(荆门)制衣有限公司",
                        "contractType":"劳动合同",
                        "contractYear":"1",
                        "startDate":"2022-06-04",
                        "endDate":"2023-06-04",
                        "qdDate":"2022-06-04",
                        "zzDate":"",//合同终止日期
                        "qdNum":1,//签订次数
                        "xqspState":"未发起",
                        "htState":"已生效",//合同状态
                        "id": 1339250080323
                        }
                    ],
                "hasPrevPage": false,
                "hasNextPage": true
            }}; 
            resolve(tempData);
        }, 200);
    });
};

//表格多选事件
const tableSelection = (data: EmptyObjectType[]) => {
	// console.log('表格多选事件', data)
	state.selectlist = data;
};
// 拖动显示列排序回调
const onSortHeader = (data: object[]) => {
	tb.tableData.columns = data;
};
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	tb.tableData.param = Object.assign({}, tb.tableData.param, { ...data });
	nextTick(() => {
		tableRef.value.pageReset();
	});
};

const exportChangeData = (data: Array<EmptyObjectType>) => {
	data.forEach((item) => {
		item.sysFlag = item.sysFlag == 1 ? '是' : '否';
	});
	return data;
};
// 查询机构数据
const loadOrgData = async () => {
	state.loading = true;
	var res = await getAPI(SysOrgApi).apiSysOrgListGet(0);
	console.log(res);
	state.orgTreeData = res.data.result ?? [];
	state.loading = false;
};

// 查询操作
const handleQuery = async () => {
	state.loading = true; 
	nextTick(() => {
		tableRef.value.pageReset();
	});
	state.loading = false;
};

// 打开新增页面
const openAddUser = () => {
	state.editUserTitle = '添加账号';
	editUserRef.value?.openDialog({});
};

// 打开编辑页面
const openEditEmployee = (row: any) => {
	state.editUserTitle = '编辑账号';
	editUserRef.value?.openDialog(row);
};

// 删除
const delUser = (row: any) => {
	ElMessageBox.confirm(`确定删除员工记录：【${row.realName}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(EmployeeApi).apiEmployeeDeletePost({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 树组件点击
const nodeClick = async (node: any) => {
	tb.tableData.param.orgId = node.id;
	tb.tableData.param.jobNum = undefined;
	tb.tableData.param.realName = undefined;
	tb.tableData.param.phone = undefined;
	handleQuery();
};

onMounted(async () => {
	loadOrgData();
});
</script>
<style>
.tabSearch_Bar .mb20{
	margin-bottom: 10px !important;
}
.spaceDropDown.el-dropdown{
  margin-left: 10px;
  margin-right: 10px;
}

.contract_tip_bar{
    width: 100%; 
    border-radius: 0px;
    background-color: rgba(247, 231, 179, 0.6);
    border:solid 1px #f5be49
}
.contract_tip_bar .el-card__body{
    padding: 5px 20px;
}
.contract_tip_bar .el-col{
    line-height: 23px;
    height: 23px;
    color: #666666;
}
.contract_tip_bar .tipNum{
    color:rgb(243, 21, 21);
    font-weight: bold;
}
.mgright{
    text-align: right;
}
.mgright i{
    cursor: pointer;
}
.mgright i:hover{
    color: red;
}
.settingnotice{
    color: #306cda;
    text-decoration: underline;
    cursor: pointer;
    padding-left: 15px;
}
.settingnotice:hover{
    color: #035191;
}
</style>